﻿using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using BO.Infrastructure.Config;
using BO.Infrastructure.Utils;
using Utilities.Entities;
using System;
using BugManager;

namespace BO.Solr
{
    public class SolrBO_NoCache
    {

        #region Core
        public class SolrFeature
        {
            public class DataTypes
            {
                public const string JSON = "json";

                public static string DistributionDate = "DistributionDate";
            }

            public static string GetFeature_rows(int rows)
            {
                return string.Format("&rows={0}", rows);
            }

            public static string GetFeature_start(int startIndex)
            {
                return string.Format("&start={0}", startIndex);
            }

            public static string GetFeature_tags(string tagUrl)
            {
                return string.Format("&Tags:\"{0}\"", tagUrl.ToLower());
            }

            public static string GetFeature_keywords(string keywords, bool exactlySearching = true)
            {
                //var result = string.Format("Title:\"{0}\"+OR+Sapo:\"{0}\"+OR+InitSapo:\"{0}\"+OR+Tags:\"{0}\"", keywords);
                //return exactlySearching ? result : result.Replace("\"", string.Empty);
                if (exactlySearching)
                    return string.Format("Title:\"{0}\"+OR+Sapo:\"{0}\"+OR+InitSapo:\"{0}\"+OR+Tags:\"{0}\"", keywords);
                keywords = Regex.Replace(keywords, "[^a-zA-Z0-9]+", "+");
                return string.Format("Title:{0}+OR+Tags:{0}", keywords);
            }

            public static string GetFeature_wt(string dataType)
            {
                return string.Format("&wt={0}", dataType);
            }

            public static string GetFeature_sort(string dataType)
            {
                return string.Format("&sort={0} desc", dataType);
            }
        }

        public static SearchResult MakeRequest(string query)
        {
            try
            {
                query = AppSettings.SolrDomain.TrimEnd('/') + "/solr/soha/select?q=" + query.TrimStart('&');
                var request = WebRequest.Create(query);
                request.Timeout = 3000;
                var response = (HttpWebResponse)request.GetResponse();

                var stream = response.GetResponseStream();

                if (stream != null)
                {
                    var reader = new StreamReader(stream, Encoding.UTF8);
                    var responseText = reader.ReadToEnd();
                    reader.Close();
                    response.Close();

                    if (!string.IsNullOrEmpty(responseText))
                    {
                        return PresentationUtils.JsonToObject<SearchResult>(responseText);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("SolrBO_NoCache", "MakeRequest", string.Format("Query : {0} | {1}", query, ex));
            }
            return null;
        }
        #endregion

        public static SearchResult SearchNewsByTag(string tagUrl, int pageIndex, int pageSize, int topExclusion = 0)
        {
            var sb = new StringBuilder();
            sb.Append(SolrFeature.GetFeature_tags(tagUrl));
            sb.Append(SolrFeature.GetFeature_start((pageIndex - 1) * pageSize + topExclusion));
            sb.Append(SolrFeature.GetFeature_rows(pageSize));
            sb.Append(SolrFeature.GetFeature_wt(SolrFeature.DataTypes.JSON));
            sb.Append(SolrFeature.GetFeature_sort(SolrFeature.DataTypes.DistributionDate));
            return MakeRequest(sb.ToString());
        }


        public static SearchResult SearchNewsByKeywords(string keywords, int pageIndex, int pageSize, bool exactlySearching = true)
        {
            var sb = new StringBuilder();
            sb.Append(SolrFeature.GetFeature_keywords(keywords, exactlySearching));
            sb.Append(SolrFeature.GetFeature_start((pageIndex - 1) * pageSize));
            sb.Append(SolrFeature.GetFeature_rows(pageSize));
            sb.Append(SolrFeature.GetFeature_wt(SolrFeature.DataTypes.JSON));
            sb.Append(SolrFeature.GetFeature_sort(SolrFeature.DataTypes.DistributionDate));
            return MakeRequest(sb.ToString());
        }
    }
}
